import React, { Component } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import moment from 'moment';
import { Form, Input, Button, notification, Select, Col, Row, Cascader, DatePicker, message } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";
import OneItem from './OneItem';

import MaintenanceModal from './MaintenanceModal';
import PropertyModal from './PropertyModal';

import { DICT } from '../enum';
import Imgviewer from '@/components/ImgViewer';
import { DropDownSelect } from '@/components/DropDownSelect/index';
import { judgeAreaFn } from '@/utils/judgeArea.js'

const { Option } = Select;

interface Props extends FormComponentProps {
  dispatch?: Function,
  data?: {
    id: number,
    x: number,
    y: number,
    areaId: number,
    image: string,
    registerTime: string,
    fireOwnerName: string,
    maintenanceOwnerName: string,
    propertyOwnerName: string,
    areaName: string
  },
  img?: {
    url: string,
    message: string,
  },
  keys?: Array<string>,
  dict?: any,
  provice?: Array<any>,
  sub?: Array<any>,
}

function getOption(obj) {
  const children = [];
  let { entries } = Object;

  for (let [key, value] of entries(obj)) {
    children.push(<Option key={key}>{value}</Option>);
  }

  return children;
}

@connect(({ owner, location, upload }) => ({
  dict: owner.dict,
  img: upload.imgValue,
  provice: location.provice,
  sub: location.sub
}))
class FormItem extends Component<Props, any> {
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
    isNew: true,
    fireVisible: false,
    maintenanceVisible: false,
    propertyVisible: false,
    fireOwnerName: '',
    maintenanceOwnerName: '',
    propertyOwnerName: '',
    option: [],
    defAreaId: '',
    areaId: [],
    areaName: '请选择'
  };

  componentDidMount() {
    const { data, form, dispatch, provice } = this.props;
    dispatch({
      type: 'owner/init', payload: {
        dict: { keyList: DICT },
        url: data ? data.image : null
      }
    }).then(() => {
      this.setState({ option: provice })
    });
    if (data) {
      const { id, x, y, areaId, areaName, image, registerTime, fireOwnerName, maintenanceOwnerName, propertyOwnerName, ...items } = data;
      const ans = {
        position: `${x || ''},${y || ''}`,
        registerTime: registerTime ? moment(registerTime, 'YYYY-MM-DD') : null,
        areaId: [areaId],
        ...items
      };
      form.setFieldsValue(ans);

      this.setState({ fireOwnerName, maintenanceOwnerName, propertyOwnerName, defAreaId: areaId, areaName })
    }
  }

  uploadImage(e) {
    e.persist();
    const { dispatch } = this.props;
    const file = e.target.files[0];
    dispatch({ type: 'upload/uploadImg', payload: file });
  }

  setFire(data) {
    if (data && data.id) {
      const { form } = this.props;
      form.setFieldsValue({ fireOwnerId: data.id })
    }
    this.setState({ fireVisible: false, fireOwnerName: data && data.name ? data.name : '' })
  }

  setProperty(data) {
    if (data && data.id) {
      const { form } = this.props;
      form.setFieldsValue({ propertyOwnerId: data.id })
    }
    this.setState({ propertyVisible: false, propertyOwnerName: data && data.name ? data.name : '' })
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form, data, dispatch, img } = this.props;
    form.validateFields((err, values) => {
      values.areaId = judgeAreaFn(message, this);
      if (values.areaId === false) {
        return;
      }
      // if(this.state.areaId.length === 0 && !this.state.defAreaId) {
      //   message.warning('请选择所属区域');
      //   return;
      // }else if(this.state.areaId.length !== 0 && this.state.areaId.length < 3) {
      //   message.warning('请选择至街道');
      //   return;
      // } else if (!this.state.areaId) {
      //   values.areaId = this.state.defAreaId;
      // }else {
      //   let len = this.state.areaId.length - 1;
      //   values.areaId = this.state.areaId[len];
      // }
      if (!err) {
        message.loading('', 0.5);
        const { position, registerTime, ...res } = values;
        const ans = {
          x: position.split(',')[0],
          y: position.split(',')[1],
          image: img.url,
          registerTime: values.registerTime ? moment(values.registerTime).format("YYYY-MM-DD HH:mm:ss") : null,
          ...res
        };
        dispatch({
          type: 'owner/update',
          payload: {
            id: data.id,
            ...ans
          }
        })
      } else {
        notification['error']({
          message: `修改失败`,
          description: '字段验证不通过',
        });
      }
    })
  }

  loadData = (selectedOptions) => {
    const { dispatch, provice } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    if (+targetOption.value < 1e8) {
      dispatch({ type: 'location/querySubordinate', payload: targetOption.value }).then(() => {
        targetOption.loading = false;
        targetOption.children = this.props.sub;
        const op = this.state.option || provice;
        this.setState({
          option: [...op],
        });
      })
    }
  };

  onChangeCascader = (value) => {
    this.setState({
      areaId: value
    })
  };

  render() {
    const { form, dict = {}, img } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 4,
        },
      },
    };
    return (
      <Form onSubmit={this.handleSubmit}>
        <Row>
          <Col span={12}>
            <OneItem title='单位名称' require={true} type='name' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='单位简介' require={true} type='intro' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='单位地址' require={true} type='address' form={form} />
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='所属区域'
            >
              {getFieldDecorator('areaId', {
                rules: [{ required: true, message: '请选所属区域' }],
              })(
                <div>
                  <Cascader
                    options={this.state.option || this.props.provice}
                    loadData={this.loadData}
                    changeOnSelect
                    placeholder={this.state.areaName}
                    onChange={this.onChangeCascader}
                  />
                </div>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='单位类型'
            >
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '请选择单位类型', whitespace: true }],
              })(
                <Select
                  placeholder="单位类型"
                >
                  {dict['owner.type'] ? getOption(dict['owner.type']) : null}
                </Select>
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='单位属性'
            >
              {getFieldDecorator('flag', {
                rules: [{ required: true, message: '请选择单位属性', whitespace: true }],
              })(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                >
                  {dict['owner.flag'] ? getOption(dict['owner.flag']) : null}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='消防安全负责人' require={true} type='fireSafetyManagerName' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='单位所属中心名称' require={false} type='centerOwnerName' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='所属行业' require={true} type='industry' form={form} />
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='单位坐标采集'
            >
              {getFieldDecorator('position', {
                rules: [{ required: true, message: '请输入单位坐标' }],
              })(
                <Input style={{ width: '76%' }} placeholder='请输入单位坐标' />
              )}
              <a target="_blank" rel="百度坐标拾取" href="http://api.map.baidu.com/lbsapi/getpoint/index.html">
                坐标拾取
              </a>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='单位图片'
            >
              <input style={{ opacity: 0, width: 120, zIndex: 10, position: 'absolute', cursor: 'pointer' }} onChange={(e) => { this.uploadImage(e) }} type="file" accept="image/*" />
              <Button style={{ marginTop: -50 }}>上传缩略图</Button>
              <Imgviewer hasText="查看平面图" missText="暂无平面图" url={img.url} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='所含设备类型'
            >
              {getFieldDecorator('ownerTags', {
                rules: [{ required: false, message: '请选择设备类型' }]
              })(
                DropDownSelect(dict, 'owner.tags', 'multiple', '100%', null, null, null, true)
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='法人姓名' require={true} type='corporation' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='法人电话' require={true} type='corporationMobile' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='邮政编码' require={true} type='postalCode' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='单位邮箱' require={true} type='ownerEmail' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='单位占地面积（平方米）' require={true} type='floorSpace' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='防火机构人数' require={true} type='fireOwnerNum' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='维保单位'
            >
              {getFieldDecorator('maintenanceOwnerId')(
                <Input style={{ display: 'none' }} placeholder='请选择维保单位' disabled />
              )}
              <span>{this.state.maintenanceOwnerName}</span>
              <Button onClick={() => this.setState({ maintenanceVisible: true })}>选择</Button>
            </Form.Item>
          </Col>
          <Col span={12}>
            <OneItem title='维保联系人' require={true} type='maintenanceContactUser' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='维保联系电话' require={true} type='maintenanceContactMobile' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='消防主机品牌型号' require={true} type='fireHostBrandModel' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='消控室网络情况' require={true} type='fireRoomNetCase' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='消控室网络运营商' require={true} type='fireRoomNetOperator' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='宽带账号' require={true} type='fireRoomNetAccount' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='宽带密码' require={true} type='fireRoomNetPwd' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item {...formItemLayout} label="注册时间">
              {getFieldDecorator('registerTime', {
                rules: [{ required: true, message: '请输入注册时间' }],
              })(
                <DatePicker {...getFieldDecorator('registerTime')} placeholder="选择注册时间" style={{ width: '95%' }} />
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <OneItem title='重点工种' require={false} type='keyOffer' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='消控室位置' require={true} type='fireRoomPosition' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='消控室联系人' require={true} type='fireRoomContactUser' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='消控室联系电话' require={true} type='fireRoomContactMobile' form={form} />
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='物业单位'
            >
              {getFieldDecorator('propertyOwnerId')(
                <Input style={{ display: 'none' }} placeholder='请选择物业单位' disabled />
              )}
              <span>{this.state.propertyOwnerName}</span>
              <Button onClick={() => this.setState({ propertyVisible: true })}>选择</Button>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='专兼职消防管理人' require={true} type='proFireManagerName' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='专兼职消防管理人电话' require={true} type='proFireManagerMobile' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='监管等级'
            >
              {getFieldDecorator('monitorLevel')(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择监管等级"
                >
                  {dict['owner.regulatoryLevel'] ? getOption(dict['owner.regulatoryLevel']) : null}
                </Select>
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <OneItem title='统一社会信用代码' require={false} type='socialCreditCode' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='消防安全负责人电话' require={true} type='fireSafetyManagerMobile' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='单位资产（万）' require={false} type='asset' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='人数规模' require={false} type='peopleScale' form={form} />
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='安全等级'
            >
              {getFieldDecorator('safetyLevel')(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                >
                  {dict['owner.safetyLevel'] ? getOption(dict['owner.safetyLevel']) : null}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='单位代码'
            >
              {getFieldDecorator('ownerCode')(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                >
                  {dict['owner.code'] ? getOption(dict['owner.code']) : null}
                </Select>
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='经济类型'
            >
              {getFieldDecorator('economicType')(
                DropDownSelect(dict, 'economic.type')
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='专职消防队数量' require={false} type='proFireBrigadeNum' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='义务消防队数量' require={false} type='dutyFireBrigadeNum' form={form} />
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='防火安全制度名称' require={false} type='safetySystemName' form={form} />
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label='防火安全制度类别'
            >
              {getFieldDecorator('safetySystemType')(
                <Select
                  style={{ width: '100%' }}
                  placeholder="请选择"
                >
                  {dict['owner.system.type'] ? getOption(dict['owner.system.type']) : null}
                </Select>
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <OneItem title='备注' require={false} type='remark' form={form} />
          </Col>
          <Col span={12}>
            <OneItem title='重点部位' require={false} type='keySite' form={form} />
          </Col>
        </Row>
        <Row>

        </Row>
        <Form.Item {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">修改</Button>
          <Link to='/data/owner'>
            <Button style={{ marginLeft: '5%' }}>返回列表</Button>
          </Link>
        </Form.Item>
        <MaintenanceModal
          visible={this.state.maintenanceVisible}
          cancelMaintenance={() => this.setState({ maintenanceVisible: false })}
          setMaintenance={(data) => this.setMaintenance(data)}
        />
        <PropertyModal
          visible={this.state.propertyVisible}
          cancelProperty={() => this.setState({ propertyVisible: false })}
          setProperty={(data) => this.setProperty(data)}
        />
      </Form>
    );
  }
}

const FormList = Form.create()(FormItem);
export default FormList;
